package handler

import (
	"context"
	"gitee.com/w5681688/cart/domian/model"
	service2 "gitee.com/w5681688/cart/domian/service"
	. "gitee.com/w5681688/cart/proto/cart"
	"gitee.com/w5681688/common"
)

type Cart struct {
	CartService service2.ICartService
}

func (c *Cart) AddCart(ctx context.Context, request *CartInfo, response *AddResponse) (err error) {
	cart := &model.Cart{}
	common.SwapTo(request, cart)
	response.CartId, err = c.CartService.AddCart(cart)
	return err
}

func (c *Cart) ClearCart(ctx context.Context, request *Clean, response *Response) error {
	if err := c.CartService.ClearCart(request.UserId); err != nil {
		return err
	}
	response.Msg = "清空购物车成功"
	return nil
}

func (c *Cart) Incr(ctx context.Context, request *Item, response *Response) error {
	if err := c.CartService.IncrNum(request.Id, request.ChangeNum); err != nil {
		return err
	}
	response.Msg = "清空购物车成功"
	return nil
}

func (c *Cart) Decr(ctx context.Context, request *Item, response *Response) error {
	if err := c.CartService.DecrNum(request.Id, request.ChangeNum); err != nil {
		return err
	}
	response.Msg = "减少购物车成功"
	return nil
}

func (c *Cart) DeleteItemById(ctx context.Context, request *CartId, response *Response) error {
	if err := c.CartService.DeleteCart(request.Id); err != nil {
		return err
	}
	response.Msg = "购物车删除成功"
	return nil
}

func (c *Cart) GetALL(ctx context.Context, request *CartFindALL, response *CartALL) error {
	cartAll, err := c.CartService.FindAllCart(request.UserId)
	if err != nil {
		return err
	}
	for _, v := range cartAll {
		cart := &CartInfo{}
		if err := common.SwapTo(v, cart); err != nil {
			return err
		}
		response.CartInfo = append(response.CartInfo, cart)
	}
	return nil
}
